package com.hnkywl.sts.service.jhgl;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.hnkywl.sts.dao.jhgl.*;
import com.hnkywl.sts.entity.jhgl.*;
import com.hnkywl.sts.service.base.BmService;
import com.hnkywl.sts.service.htgl.CghtService;
import com.hnkywl.sts.service.sys.YgService;
import com.hnkywl.sts.util.BaseUtils;
import net.ruixin.orm.hibernate.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: ZHUCHG
 * Date: 13-4-2
 * Time: 下午9:49
 * To change this template use File | Settings | File Templates.
 */
@Service
public class WzjhService {
    private XyService xyService;
    private CgwzjhDao cgwzjhDao;
    private TpwzjhDao tpwzjhDao;
    private ZgwzjhDao zgwzjhDao;
    private ZgwzjhmxDao zgwzjhmxDao;
    private TpwzjhmxDao tpwzjhmxDao;
    private CghtService cghtService;
    private BmService bmService;

    /**
     * @param type     计划类型
     * @param jhnf     计划年份
     * @param jhyf     计划月份
     * @param jhbh     计划编号
     * @param sbgsId   申报公司ID
     * @param gysId    供应商ID
     * @param spzt     审批状态
     * @param tcgsId   统筹公司ID
     * @param pageNo
     * @param pageSize
     * @return
     */
    public String findList(String type, String jhnf, String jhyf, String jhbh, Long sbgsId, Long gysId, String spzt, Long tcgsId, String wzbm, int pageNo, int pageSize) {
        //Page<? extends Cgwzjh> page = null;
        Page<Map> page = null;
        String json = null;
        if ("Cgwzjh".equals(type)) {
            page = cgwzjhDao.findList(jhnf, jhyf, jhbh, sbgsId, gysId, spzt, tcgsId, wzbm, pageNo, pageSize);
            //计划单号   供应商  类型 申报机构  申报数量 备注  创建人  创建时间 审批
            //json = BaseUtils.fetchCollectionToJson(page.getResult(), "id", "jhbh", "gys.qc", "sbgs.qc", "sbjg.qc", "sbsl", "bz", "zdr.xm", "zdsj");
            Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
            json = gson.toJson(page.getResult());
        }
        if ("Tpwzjh".equals(type)) {
            page = tpwzjhDao.findList(jhnf, jhyf, jhbh, sbgsId, gysId, spzt, tcgsId, wzbm, pageNo, pageSize);
            //计划单号   供应商  类型 申报机构  付款方式 申报数量 备注  创建人  创建时间 审批
            // json = BaseUtils.fetchCollectionToJson(page.getResult(), "id", "jhbh", "gys.qc", "sbgs.qc", "sbjg.qc", "sbsl", "bz", "zdr.xm", "zdsj");
            Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
            json = gson.toJson(page.getResult());
        }
        if ("Zgwzjh".equals(type)) {
            page = zgwzjhDao.findList(jhnf, jhyf, jhbh, sbgsId, gysId, spzt, tcgsId, wzbm, pageNo, pageSize);
            //计划单号   供应商  类型 申报机构  付款方式 自购模式  备注  创建人  创建时间 审批
            // json = BaseUtils.fetchCollectionToJson(page.getResult(), "id", "jhbh", "gys.qc", "sbgs.qc", "sbjg.qc", "sbsl", "bz", "zdr.xm", "zdsj");
            Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
            json = gson.toJson(page.getResult());
        }
        return "{\"total\":" + page.getTotalCount() + ",\"rows\":" + json + "}";
    }

    /**
     * 首页物资计划数
     *
     * @return
     */
    public String findAllWzjh() {
        Integer wzjhNum = 0;
        try {
            Date aDate = new Date(System.currentTimeMillis());
            Calendar calendar = GregorianCalendar.getInstance();
            calendar.setTime(aDate);
            Integer year = calendar.get(Calendar.YEAR);    //获取年
            Integer month = calendar.get(Calendar.MONTH) + 2;   //获取月份，0表示1月份
            return cgwzjhDao.findWzjhSum(year.toString(), month.toString(), "ybc");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return wzjhNum.toString();
    }

    @Transactional
    public void saveCgwzjh(Cgwzjh cgwzjh) {
        cgwzjhDao.save(cgwzjh);
    }

    /**
     * 保存自购物资计划
     *
     * @param zgwzjh
     * @param zgwzjhmxList
     */
    @Transactional
    public void saveZgwzjh(Zgwzjh zgwzjh, List<Zgwzjhmx> zgwzjhmxList) {

        String ssgsbm = zgwzjh.getSbgs().getBm();
        Long ssgsId = zgwzjh.getSbgs().getId();
        zgwzjh.setJhbh(bmService.getWzjhbm("ZGWZJH"));
        initZgwzjh(zgwzjh);
        //计算申报数量
        zgwzjh.setSbsl(sumZgwzjh(zgwzjhmxList));
        zgwzjh.setCreateUser(YgService.getCurrentYg());
        zgwzjh.setCreateOrgan(YgService.getCurrentYg().getZggs());
        zgwzjh.setCreateDepartment(YgService.getCurrentYg().getZgjg());
        zgwzjh.setDateCreated(new Date());
        zgwzjh.setLastUpdated(zgwzjh.getDateCreated());
        //保存自购物资计划
        zgwzjhDao.save(zgwzjh);
        if (zgwzjhmxList != null) {
            for (Zgwzjhmx temp : zgwzjhmxList) {
                temp.setZgwzjh(zgwzjh);
                if (temp.getCd().getId() == null)
                    temp.setCd(null);
                zgwzjhmxDao.save(temp);
            }
        }
    }

    private Double sumZgwzjh(List<Zgwzjhmx> zgwzjhmxList){
        if (zgwzjhmxList == null) return 0.00;
        Double sum = 0.0;
        for(Zgwzjhmx zgwzjhmx : zgwzjhmxList){
            sum += zgwzjhmx.getSbsl();
        }
        return sum;
    }

    private void initZgwzjh(Zgwzjh zgwzjh){
        if (zgwzjh.getXy()!=null && zgwzjh.getXy().getId() == null)
            zgwzjh.setXy(null);
        if (zgwzjh.getGys()!=null && zgwzjh.getGys().getId() == null)
            zgwzjh.setGys(null);
        if (zgwzjh.getKh()!=null && zgwzjh.getKh().getId() == null)
            zgwzjh.setKh(null);
        if (zgwzjh.getDbf()!=null && zgwzjh.getDbf().getId() == null)
            zgwzjh.setDbf(null);
        if (zgwzjh.getLj()!=null && zgwzjh.getLj().getId() == null)
            zgwzjh.setLj(null);
        if (zgwzjh.getSbgs()!=null && zgwzjh.getSbgs().getId() == null)
            zgwzjh.setSbgs(null);
        if (zgwzjh.getSbbm()!=null && zgwzjh.getSbbm().getId() == null)
            zgwzjh.setSbbm(null);
    }


    /**
     * 修改自购物资计划
     *
     * @param zgwzjh
     * @param zgwzjhmxList
     */
    @Transactional
    public void editZgwzjh(Zgwzjh zgwzjh, List<Zgwzjhmx> zgwzjhmxList) {
        Zgwzjh z = zgwzjhDao.get(zgwzjh.getId());


        z.setXqnf(zgwzjh.getXqnf());
        z.setXqyf(zgwzjh.getXqyf());
        z.setJhsl(zgwzjh.getJhsl());
        z.setJhdw(zgwzjh.getJhdw());
        z.setSbgs(zgwzjh.getSbgs());
        z.setSbbm(zgwzjh.getSbbm());
        z.setZbcg(zgwzjh.getZbcg());
        z.setCggs(zgwzjh.getCggs());
        z.setSbsl(sumZgwzjh(zgwzjhmxList));
        z.setLastUpdated(new Date());
        //保存自购物资计划
        zgwzjhDao.save(z);

        List<Zgwzjhmx> mxList = zgwzjhmxDao.findZgwzjhmxByZgwzjh(z.getId());
        for (Zgwzjhmx mx : mxList)
            zgwzjhmxDao.delete(mx.getId());

        if (zgwzjhmxList != null) {
            for (Zgwzjhmx temp : zgwzjhmxList) {
                temp.setZgwzjh(z);
                //规格
                if (temp.getWzgg().getId() == null)
                    temp.setWzgg(null);
                //产地
                if (temp.getCd().getId() == null)
                    temp.setCd(null);
                zgwzjhmxDao.save(temp);
            }
        }
    }

    /**
     * 保存统配物资计划
     *
     * @param tpwzjh
     * @param tpwzjhmxList
     */
    @Transactional
    public void saveTpwzjh(Tpwzjh tpwzjh, List<Tpwzjhmx> tpwzjhmxList) {
        try {
            tpwzjh.setJhbh(bmService.getWzjhbm("TPWZJH"));

            initTpwzjh(tpwzjh);

            tpwzjh.setSbsl(sumTpwzjh(tpwzjhmxList));

            //付款类型
            //tpwzjh.setFklx(xy.getGys().getJyms().getFklx());
            //保存统配物资计划

            if (tpwzjh.getXy() != null) {
                Xy xy = xyService.findXyDetail(tpwzjh.getXy().getId());
                tpwzjh.setLj(xy.getLj());
            }

            //保存统配物资计划明细
            if (tpwzjhmxList != null) {
                for (Tpwzjhmx temp : tpwzjhmxList) {
                    temp.setTpwzjh(tpwzjh);
                    if (temp.getCd().getId() == null)
                        temp.setCd(null);
                    if (temp.getJzfs().getId() == null)
                        temp.setJzfs(null);
                    tpwzjhmxDao.save(temp);
                }
            }
            tpwzjh.setDateCreated(new Date());
            tpwzjh.setLastUpdated(tpwzjh.getDateCreated());
            tpwzjh.setCreateUser(YgService.getCurrentYg());
            tpwzjh.setCreateOrgan(YgService.getCurrentYg().getZggs());
            tpwzjh.setCreateDepartment(YgService.getCurrentYg().getZgjg());
            tpwzjhDao.save(tpwzjh);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private Double sumTpwzjh(List<Tpwzjhmx> tpwzjhmxList){
        if (tpwzjhmxList == null) return 0.00;
        Double sum = 0.0;
        for(Tpwzjhmx tpwzjhmx : tpwzjhmxList){
            sum += tpwzjhmx.getSbsl();
        }
        return sum;
    }

    private void initTpwzjh(Tpwzjh tpwzjh){
        //协议
        if (tpwzjh.getXy()!=null && tpwzjh.getXy().getId() == null)
            tpwzjh.setXy(null);
        //供应商
        if (tpwzjh.getGys()!=null && tpwzjh.getGys().getId() == null)
            tpwzjh.setGys(null);
        //申报公司
        if (tpwzjh.getSbgs()!=null && tpwzjh.getSbgs().getId() == null)
            tpwzjh.setSbgs(null);
        //申报部门
        if (tpwzjh.getSbbm()!=null && tpwzjh.getSbbm().getId() == null)
            tpwzjh.setSbbm(null);
        //统筹公司
        if (tpwzjh.getTcgs()!=null && tpwzjh.getTcgs().getId() == null)
            tpwzjh.setTcgs(null);
        //统筹部门
        if (tpwzjh.getTcbm()!=null && tpwzjh.getTcbm().getId() == null)
            tpwzjh.setTcbm(null);
    }


    /**
     * 修改统配物资计划
     *
     * @param tpwzjh
     * @param tpwzjhmxList
     */
    @Transactional
    public void editTpwzjh(Tpwzjh tpwzjh, List<Tpwzjhmx> tpwzjhmxList) {
        try {
            Tpwzjh t = tpwzjhDao.get(tpwzjh.getId());
            t.setLastUpdated(new Date());
            t.setXqnf(tpwzjh.getXqnf());
            t.setXqyf(tpwzjh.getXqyf());
            t.setJhsl(tpwzjh.getJhsl());
            t.setSbsl(sumTpwzjh(tpwzjhmxList));
            t.setJhdw(tpwzjh.getJhdw());
            t.setSbgs(tpwzjh.getSbgs());
            t.setSbbm(tpwzjh.getSbbm());

            List<Tpwzjhmx> mxList = tpwzjhmxDao.findTpwzjhmxByTpwzjh(t.getId());
            for (Tpwzjhmx mx : mxList)
                tpwzjhmxDao.delete(mx.getId());

            if (tpwzjhmxList != null) {
                for (Tpwzjhmx temp : tpwzjhmxList) {
                    temp.setTpwzjh(t);
                    //规格
                    if (temp.getWzgg().getId() == null)
                        temp.setWzgg(null);
                    //产地
                    if (temp.getCd().getId() == null)
                        temp.setCd(null);
                    //计重方式
                    if (temp.getJzfs().getId() == null)
                        temp.setJzfs(null);

                    tpwzjhmxDao.save(temp);
                }
            }

            //保存统配物资计划
            tpwzjhDao.save(t);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public Cgwzjh findCgwzjh(Long id) {
        return cgwzjhDao.get(id);
    }

    public Zgwzjh findZgwzjh(Long id) {
        return zgwzjhDao.get(id);
    }


    public Tpwzjh findTpwzjh(Long id) {
        return tpwzjhDao.get(id);
    }

    @Transactional
    public Cgwzjh findWzjhDetailByProcessInstance(String processInstanceId) {
        return this.cgwzjhDao.findUniqueByProperty("processInstanceId", processInstanceId);
    }

    @Transactional
    public void updateTpwzjhmxhdsl(String tpwzjhmxList) {
        Gson gson = new Gson();
        List<Map> list = gson.fromJson(tpwzjhmxList, ArrayList.class);
        for (Map tpwzjhmx : list) {
            this.tpwzjhDao.updateTpwzjhmxhdsl(tpwzjhmx);
        }
    }


    public String findWzjhCreateZjjh(String type, Long ssgsId, String spzt, int pageNo, int pageSize) {
        String json = "";
        if ("Zgwzjh".equalsIgnoreCase(type)) {
            Page<Zgwzjh> page = zgwzjhDao.findZgwzjh(ssgsId, spzt, true, pageNo, pageSize);
            json = BaseUtils.fetchCollectionToJson(page.getResult(), "id", "jhbh", "lrbl", "lj.id", "lj.mc", "lj.lx", "xy.fkfs.z", "xy.fkfs.id", "lj.kxg", "gys.id", "gys.qc", "kh.id", "kh.qc", "dbf.id", "dbf.qc", "sbgs.id",
                    "sbbm.id", "sbgs.qc","sbgs.jc",  "sbbm.qc", "cggs.id", "cggs.qc","cggs.jc", "xqnf", "xqyf", "xqr", "sbsl", "bz", "createUser.xm", "zdsj");
//            json = BaseUtils.fetchCollectionToJson(page.getResult(), "id", "jhbh", "lrbl", "lj.id", "lj.mc", "lj.lx", "xy.fkfs.z", "xy.fkfs.id", "lj.rzlx", "lj.kxg", "gys.id", "gys.qc", "kh.id", "kh.qc", "dbf.id", "dbf.qc", "sbgs.id",
//                    "sbjg.id", "sbgs.qc", "sbjg.qc", "xqnf", "xqyf", "xqr", "sbsl", "bz", "createUser.xm", "zdsj");
            json = "{\"total\":" + page.getTotalCount() + ",\"rows\":[" + json + "]}";
        }
        if ("Tpwzjh".equalsIgnoreCase(type)) {
            Page<Tpwzjh> page = tpwzjhDao.findTpwzjhNoZjjh(ssgsId, spzt, pageNo, pageSize);
            json = BaseUtils.fetchCollectionToJson(page.getResult(), "id", "jhbh","lj.id", "lj.mc", "lj.lx", "gys.id", "gys.qc", "sbgs.id", "sbbm.id", "sbgs.qc","sbgs.jc", "sbbm.qc", "xqnf",
                    "xqyf", "xqr", "sbsl", "bz", "createUser.xm", "zdsj");
//            json = BaseUtils.fetchCollectionToJson(page.getResult(), "id", "jhbh", "gys.id", "gys.qc", "sbgs.id", "sbjg.id", "sbgs.qc", "sbjg.qc", "xqnf",
//                    "xqyf", "xqr", "sbsl", "bz", "createUser.xm", "zdsj");
            json = "{\"total\":" + page.getTotalCount() + ",\"rows\":[" + json + "]}";
        }
        return json;
    }

    public String findWzjhCreateHt(Long ssgsId, String spzt, int pageNo, int pageSize) {
        Page<Zgwzjh> page = zgwzjhDao.findZgwzjh(ssgsId, spzt, false, pageNo, pageSize);
        String json = BaseUtils.fetchCollectionToJson(page.getResult(), "id", "jhbh", "lrbl", "lj.id", "lj.mc", "lj.lx", "lj.kxg", "lj.hkq", "lj.jsfs.id", "xy.fkfs.id", "xy.jhfs", "gys.id", "gys.qc", "kh.id", "kh.qc", "dbf.id", "dbf.qc", "sbgs.id",
                "sbbm.id", "sbgs.qc", "sbgs.jc","sbbm.qc", "cggs.id", "cggs.qc","cggs.jc", "zbcg", "xqnf", "xqyf", "xqr", "sbsl", "bz", "createUser.xm", "zdsj","rzlx");
//        String json = BaseUtils.fetchCollectionToJson(page.getResult(), "id", "jhbh", "lrbl", "lj.id", "lj.mc", "lj.lx", "lj.rzlx", "lj.kxg", "xy.fkfs.id", "xy.jhfs", "gys.id", "gys.qc", "kh.id", "kh.qc", "dbf.id", "dbf.qc", "sbgs.id",
//                "sbjg.id", "sbgs.qc", "sbjg.qc", "xqnf", "xqyf", "xqr", "sbsl", "bz", "createUser.xm", "zdsj");
        json = "{\"total\":" + page.getTotalCount() + ",\"rows\":[" + json + "]}";
        return json;
    }


    @Transactional
    public void deleteZgwzjh(Long id) {
        Zgwzjh z = zgwzjhDao.get(id);
        for (Zgwzjhmx mx : z.getZgwzjhmxList()) {
            mx.setDeleted(1);
            mx.setLastUpdated(new Date());
        }
        z.setDeleted(1);
        zgwzjhDao.save(z);
    }

    @Transactional
    public void deleteTpwzjh(Long id) {
        try {
            //删除统配物资计划
            Tpwzjh t = tpwzjhDao.get(id);
            for (Tpwzjhmx mx : t.getTpwzjhmxList()) {
                mx.setDeleted(1);
                mx.setLastUpdated(new Date());
            }
            t.setDeleted(1);
            tpwzjhDao.save(t);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String findZgwzjhmxByZgwzjh(Long id) {
        Zgwzjh zgwzjh = zgwzjhDao.get(id);
        String json = BaseUtils.fetchCollectionToJson(null, false, zgwzjh.getZgwzjhmxList(), "wzgg.id", "wzgg.code", "wzgg.name", "wzgg.ggxh","wzgg.cz","ggxh", "wzgg.dw", "cd.id", "cd.z", "sbsl");
        json = "{\"rows\":[" + json + "],\"footer\":[{\"cd.z\":\"合计\",\"sbsl\":" + zgwzjh.getSbsl() + "}]}";
        return json;
    }

    public String findTpwzjhmxByTpwzjh(Long id) {
        Tpwzjh tpwzjh = tpwzjhDao.get(id);
        String json = BaseUtils.fetchCollectionToJson(null, false, tpwzjh.getTpwzjhmxList(), "id", "wzgg.id", "wzgg.code","ggxh", "wzgg.name", "wzgg.ggxh", "wzgg.cz","wzgg.dw", "cd.id", "cd.z", "ck", "jzfs.id", "jzfs.z", "sbsl", "hdsl", "bz");
        json = "{\"rows\":[" + json + "],\"footer\":[{\"jzfs.z\":\"合计\",\"sbsl\":" + tpwzjh.getSbsl() + ",\"hdsl\":" + tpwzjh.getTphdsl() + "}]}";
        return json;
    }

    @Autowired
    public void setCgwzjhDao(CgwzjhDao cgwzjhDao) {
        this.cgwzjhDao = cgwzjhDao;
    }

    @Autowired
    public void setTpwzjhmxDao(TpwzjhmxDao tpwzjhmxDao) {
        this.tpwzjhmxDao = tpwzjhmxDao;
    }

    @Autowired
    public void setTpwzjhDao(TpwzjhDao tpwzjhDao) {
        this.tpwzjhDao = tpwzjhDao;
    }

    @Autowired
    public void setZgwzjhDao(ZgwzjhDao zgwzjhDao) {
        this.zgwzjhDao = zgwzjhDao;
    }

    @Autowired
    public void setZgwzjhmxDao(ZgwzjhmxDao zgwzjhmxDao) {
        this.zgwzjhmxDao = zgwzjhmxDao;
    }

    @Autowired
    public void setCghtService(CghtService cghtService) {
        this.cghtService = cghtService;
    }

    @Autowired
    public void setXyService(XyService xyService) {
        this.xyService = xyService;
    }

    @Autowired
    public void setBmService(BmService bmService) {
        this.bmService = bmService;
    }
}
